const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const { SuccessModel, FailModel } = require('../utils/resModel')
const { getPassword } = require('../utils/crypto')
const { secret_code } = require('../utils/config')
const { createCode } = require('../utils/svgCaptcha')
const { exec } = require('../utils/exec')

router.get('/', async (ctx, next) => {
  ctx.body = {
    code: 0,
    msg: 'koa',
  }
})

// 测试接口
router.get('/api/users/get-test', async (ctx, next) => {
  try {
    // 校验
    ctx.body = new SuccessModel({ msg: 'get-test' })
  } catch (err) {
    ctx.body = new FailModel(err)
  }
})

// 登陆校验码接口
router.get('/api/users/loginCode', async (ctx, next) => {
  try {
    // 生成校验码
    const info = createCode()
    // 任务一个人进入页面看到的验证码都可以存储起来，让用户在登录的时候，带上访问
    const sql = `insert into code (text) values (?)`
    const insertData = await exec(sql, [info.text])
    ctx.body = new SuccessModel({
      insertId: insertData.insertId,
      text: info.text,
      data: info.data,
    })
  } catch (err) {
    ctx.body = new FailModel('fail')
  }
})

// 登陆
router.post('/api/users/login', async (ctx, next) => {
  // 1. 拿参数
  const { username, password, text, codeId } = ctx.request.body
  try {
    const codeSql = `select * from code where codeId = ? and text=?`
    const codeData = await exec(codeSql, [codeId, text])
    console.log('codeData:', codeData)
    if (codeData.length === 0) {
      ctx.body = new FailModel('验证码有错误，请重新输入')
      return
    }
    // 2. 数据库中查找
    const sql = `select * from users where username=? and password=?`
    const loginData = await exec(sql, [username, getPassword(password)])
    const token = jwt.sign(
      {
        id: loginData[0].id,
        username: loginData[0].username,
      },
      secret_code,
      { expiresIn: '24h' }
    )
    console.log('loginData:', loginData)
    ctx.body = new SuccessModel({ token })
  } catch (err) {
    ctx.body = new FailModel('登陆错误，请重新尝试', err)
  }
})

// 注册
router.post('/api/users/register', async (ctx, next) => {
  // 1. 拿参数
  const { username, password, nickname, gender, avatar } = ctx.request.body
  try {
    // 2. 数据库中查找
    const sql = `insert into users 
    (username, password, nickname, gender, avatar) 
    values (?,?,?,?,?)`
    const registerData = await exec(sql, [
      username,
      getPassword(password),
      nickname,
      gender,
      avatar,
    ])
    ctx.body = new SuccessModel(registerData)
  } catch (err) {
    ctx.body = new FailModel('注册失败，请重新尝试', err)
  }
})

// 用户查询接口 分页
router.get('/api/users/list', async (ctx, next) => {
  const { page = 1, size = 5 } = ctx.query
  /**
   * @fun 添加权限
   * 1. 拿到用户信息 ctx.state.userInfo => id
   * 2. id =1 是超级管理员
   * 3. id !==1 的时候，每个人只能拿到拿到每个人自己的数据
   */
  try {
    const { id } = ctx.state.userInfo
    let totalSql = `select count(id) as total from users;`
    let sql = `select * from users where 1+1 `
    let userData
    if (id !== 1) {
      sql += `and id = ?`
      userData = await exec(sql, [id])
    } else {
      sql += `limit ? offset ?`
      userData = await exec(sql, [size * 1, (page - 1) * size * 1])
    }
    const total = await exec(totalSql)
    ctx.body = new SuccessModel({ total: total[0].total, userData })
  } catch (err) {
    ctx.body = new FailModel(err)
  }
})

// 模糊搜索接口
router.get('/api/users/search', async (ctx, next) => {
  const { keywords } = ctx.query
  try {
    const sql = `select * from users where username like '%${keywords}%'`
    const data = await exec(sql)
    ctx.body = new SuccessModel(data)
  } catch (err) {
    ctx.body = new FailModel(err)
  }
})

module.exports = router
